module.exports = (app)->
	new ChatRemote app

class ChatRemote
	constructor: (app)->
		@app = app
		@channelService = app.get 'channelService'
		@globalChannelService = app.get 'globalChannelService'
	
	add:(uid, sid, name, flag, cb)=>
		channel = @channelService.getChannel name, flag
		username = uid.split('*')[0]
		param = {
			route: 'onAdd',
			user: 'username'
		}
		channel.pushMessage param

		if !! channel
			channel.add uid, sid
		cb @get(name, flag)

		###

		# globalChannelService // ~~~~~~~~~~~~~~~~~~~~
		globalChannelService = @globalChannelService
		await globalChannelService.add name, uid, sid, defer err
		if !!err 
			console.error "add user #{uid} into channel #{name} failed, error: #{err}"
			return
		
		globalChannelService.pushMessage 'connector', 'onAdd', param, name ,{},(err,data)->
			console.log err,'1111111111111'
			console.log data,'333333333333333'

		await globalChannelService.getMembersByChannelName 'connector', name, defer err, list
		users = []
		for user in  list
			users.push user.split('*')[0]
		cb users
		###


	get: (name, flag) =>
		users = []
		channel = @channelService.getChannel(name, flag);
		if  !! channel
			users = channel.getMembers()
		list = []
		for user in  users
			user = user.split('*')[0];
			list.push user;
		list
	kick:(uid, sid, name, cb)=>
		channel = @channelService.getChannel name, false
		 # leave channel
		if !! channel
			channel.leave(uid, sid);
		
		username = uid.split('*')[0]
		param = {
			route: 'onLeave',
			user: username
		}
		channel.pushMessage param
		cb()

